<template>
  <img :src="imgUrl" class="file-icon" />
</template>

<script lang="ts" setup>
  import { ref, watch } from 'vue';

  const props = defineProps({
    fileName: String,
    type: String,
  });

  const iconList = {
    doc: new URL('../../assets/images/file_icon/word.png', import.meta.url).href,
    xls: new URL('../../assets/images/file_icon/excel.png', import.meta.url).href,
    ppt: new URL('../../assets/images/file_icon/ppt.png', import.meta.url).href,
    docx: new URL('../../assets/images/file_icon/word.png', import.meta.url).href,
    xlsx: new URL('../../assets/images/file_icon/excel.png', import.meta.url).href,
    csv: new URL('../../assets/images/file_icon/csv.png', import.meta.url).href,
    pptx: new URL('../../assets/images/file_icon/ppt.png', import.meta.url).href,
    txt: new URL('../../assets/images/file_icon/txt.png', import.meta.url).href,
    pdf: new URL('../../assets/images/file_icon/pdf.png', import.meta.url).href,
    html: new URL('../../assets/images/file_icon/html.png', import.meta.url).href,
    zip: new URL('../../assets/images/file_icon/zip.png', import.meta.url).href,
    '7z': new URL('../../assets/images/file_icon/zip.png', import.meta.url).href,
    tar: new URL('../../assets/images/file_icon/zip.png', import.meta.url).href,
    mp3: new URL('../../assets/images/file_icon/mp3.png', import.meta.url).href,
    mp4: new URL('../../assets/images/file_icon/mp4.png', import.meta.url).href,
  };
  const imgUrl = ref();

  function handleSuffixMap(fileName: string) {
    const curSuffix = fileName.substr(fileName.lastIndexOf('.') + 1);
    imgUrl.value = isValidKey(curSuffix, iconList) ? iconList[curSuffix] : iconList['txt'];
  }

  function isValidKey(key: string | number | symbol, object: object): key is keyof typeof object {
    return key in object;
  }

  function handleTypeMap(type: string) {
    imgUrl.value = isValidKey(type, iconList) ? iconList[type] : iconList['txt'];
  }

  watch(
    () => props.fileName,
    (value) => {
      if (value) {
        handleSuffixMap(value);
      }
    },
    { immediate: true },
  );

  watch(
    () => props.type,
    (value) => {
      if (value) {
        handleTypeMap(value);
      }
    },
    { immediate: true },
  );
</script>

<style lang="less" scoped>
  .file-icon {
    display: inline-block;
    // width: 100%;
    // height: 100%;
    width: 20px;
    height: 20px;
  }
</style>
